package com.goldfish666.remote_control.controller.base;

import com.goldfish666.remote_control.pojo.Result;
import com.goldfish666.remote_control.pojo.condition.KeywordCondition;
import com.goldfish666.remote_control.service.base.ComplexService;
import com.goldfish666.remote_control.validator.CreateValidatorGroup;
import com.goldfish666.remote_control.validator.UpdateValidatorGroup;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.constraints.NotNull;
import java.util.List;

public class AbstractCurdController<TDto, TEntity, TService extends ComplexService<TDto, TEntity, TKey>, Condition extends KeywordCondition, TKey>
        implements BaseController<TDto, Condition, TKey> {

    @Autowired
    protected TService service;

    /**
     * 条件拼接
     *
     * @param condition 筛选条件
     * @return 条件组合
     */
    protected Specification<TEntity> buildSearch(Condition condition) {
        return null;
    }

    @Override
    @ApiOperation("根据条件获取分页列表")
    public Result<? extends Page<TDto>> getFilterList(@RequestBody(required = false) @Validated Condition condition, Pageable pageable) {
        return Result.<Page<TDto>>builder().data(service.getPagedDtos(buildSearch(condition), pageable)).build();
    }

    @Override
    @ApiOperation("获取全部")
    public Result<? extends List<TDto>> getAll() {
        return Result.<List<TDto>>builder().data(service.getAllDtos()).build();
    }

    @Override
    @ApiOperation(value = "根据ID获取详情")
    public Result<TDto> getById(@PathVariable("id") @NotNull(message = "id不能为空") TKey id) {
        return Result.<TDto>builder().data(service.getDtoById(id)).build();
    }

    @Override
    @ApiOperation("根据条件获取Id集合")
    public Result<? extends List<TKey>> getIdsByFilter(@RequestBody(required = false) @Validated Condition condition) {
        return Result.<List<TKey>>builder().data(service.getIdsByFilter(buildSearch(condition))).build();
    }

    @Override
    @ApiOperation("保存")
    public Result<TDto> save(@RequestBody @Validated({CreateValidatorGroup.class}) TDto dto) {
        return Result.<TDto>builder().data(service.saveDto(dto)).build();
    }

    @Override
    @ApiOperation("更新")
    public Result<TDto> update(@RequestBody @Validated({UpdateValidatorGroup.class}) TDto dto) {
        return Result.<TDto>builder().data(service.updateDto(dto)).build();
    }

    @Override
    @ApiOperation("删除")
    public Result<Boolean> delete(@PathVariable("id") @NotNull(message = "id不能为空") TKey id) {
        return Result.<Boolean>builder().data(service.delete(id)).build();
    }
}